package com.turing.post.log.util;

import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Handler;
import java.util.logging.LogRecord;

import javax.naming.InitialContext;

import weblogic.logging.WLLogRecord;
import weblogic.workarea.WorkContext;
import weblogic.workarea.WorkContextMap;

/**
 * PCPS 日志处理器
 * 
 * @author yxb
 * 
 */
public class PCPSLogHandler extends Handler {
	public static final String PCPSCONTEXT = "PCPSCONTEXT";
	private WorkContextMap map = null;
	private ConcurrentHashMap<String, PCPSLogOut> conMap = new ConcurrentHashMap<String, PCPSLogOut>();

	public void publish(LogRecord record) {
		WLLogRecord wlLogRecord = (WLLogRecord) record;
		String scontext = null;
		synchronized (PCPSLogHandler.class) {
			if (map == null) {
				try {
					map = (WorkContextMap) new InitialContext()
							.lookup("java:comp/WorkContextMap");
				} catch (Exception ex) {
				}
			}
		}

		if (map != null) {
			WorkContext stringContext = map.get(PCPSCONTEXT);
			if (stringContext != null)
				scontext = stringContext.toString().trim();
		}

		// 不记录我们不感兴趣的日志
		if (scontext == null || scontext.length() < 1)
			return;

		PCPSLogOut logger = conMap.get(scontext);
		if (logger == null) {
			synchronized (PCPSLogHandler.class) {
				if (conMap.get(scontext) == null) {
					logger = new PCPSLogOut(scontext);
					conMap.put(scontext, logger);
				}
			}
		}
		if (logger != null)
			logger.log(wlLogRecord);
	}

	public void close() {
	}

	public void flush() {
		// for (Map.Entry<String, PCPSLogOut> entry : conMap.entrySet()){
		// PCPSLogOut logger = entry.getValue();
		// }
	}

	public static void main(String[] args) {
	}
}